/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DataElement;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.ServiceRecord;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

/**
 *
 * @author Lilli
 */
public class ServerBt implements Runnable {

    String username;
    int networkId;

    public ServerBt(String user, int networkId) {
        this.username = user;
        this.networkId = networkId;
    }

    public void run() {

        //   System.out.println("Executou o servidor");
        setServer();
    }

    public synchronized void setServer() {
        LocalDevice localDev = null;
        StreamConnectionNotifier server = null;
        StreamConnection conn = null;
        String connectionURL =
                "btspp://localhost:F0E0D0C0B0A000908070605040302010;"
                + "authenticate=false;encrypt=false;master=true;name=serviceServer";
        /*
         * Make sure the device is discoverable, else clients cannot
         * find our service
         */
        try {
            localDev = LocalDevice.getLocalDevice();
            localDev.setDiscoverable(DiscoveryAgent.GIAC);

        } catch (BluetoothStateException e) {
// Error handling code here
        }
        /*
         * First get a StreamConnectionNotifier. It is used to get
         * the service record created for us, so we can manipulate
         * the service record.
         */
        try {
            server = (StreamConnectionNotifier) Connector.open(connectionURL);
            DataElement de = new DataElement(DataElement.STRING, this.username);
            DataElement de2 = new DataElement(DataElement.STRING, this.networkId + "");
            ServiceRecord rec = localDev.getRecord(server);
            rec.setAttributeValue(0x99, de);
            rec.setAttributeValue(0x98, de2);
            localDev.updateRecord(rec);

            /*
             * acceptAndOpen() will register the service record in the
             * Bluetooth SDDB and block until a client connects.
             */
            conn = server.acceptAndOpen();

        } catch (Exception e2) {
// Error handling code here
        }
    }
}
